<?php

namespace think\admin\service;

use Alipay\EasySDK\Kernel\Config;
use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Util\ResponseChecker;
use Exception;
use think\admin\Service;

class AlipayService extends Service
{
    /**
     * App ID
     * @var string
     */
    protected string $appId;

    /**
     * Private Key
     * @var string
     */
    protected string $privateKey;

    /**
     * Public Key
     * @var string
     */
    protected string $publicKey;

    /**
     * 获取支付宝小程序码
     * @param $path
     * @param $param
     * @param string $describe
     * @return string
     */
    public function crtQrcode($path, $param, string $describe = '扫码登录'): string
    {
        //1. 设置参数（全局只需设置一次）
        Factory::setOptions($this->getAccount());
        try {
            //2. 发起API调用（以支付能力下的统一收单交易创建接口为例）
            $result = Factory::base()->qrcode()->create($path, $param, $describe);
            $responseChecker = new ResponseChecker();
            //3. 处理响应或异常
            if ($responseChecker->success($result)) {
                return $result->qrCodeUrl;
            } else {
                return '调用失败';
            }
        } catch (Exception $e) {
            return "调用失败，" . $e->getMessage() . PHP_EOL;
        }
    }

    /**
     * 支付宝小程序参数
     * @return Config
     */
    public function getAccount(): Config
    {
        $options = new Config();
        $options->protocol = 'https';
        $options->gatewayHost = 'openapi.alipay.com';
        $options->signType = 'RSA2';
        $options->appId = $this->appId;
        $options->alipayPublicKey = $this->publicKey;
        $options->merchantPrivateKey = $this->privateKey;
        return $options;
    }

    /**
     * 控制器初始化
     * @return void
     * @throws \think\admin\Exception
     */
    protected function initialize()
    {
        $this->appId = sysconfig('EMAIL_ALIYUN', 'SQM_EMAIL_ALIYUN_ACCESS_KEY_ID');
        $this->publicKey = sysconfig('EMAIL_ALIYUN', 'SQM_EMAIL_ALIYUN_PUBLIC_KEY');
        $this->privateKey = sysconfig('EMAIL_ALIYUN', 'SQM_EMAIL_ALIYUN_PRIVATE_KEY');
    }

}
